using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Xsl;


namespace FinlogiK.FxCop.Statistics.XsltTransformation
{
	/// <summary>
	/// Base class for FxCop file transformers.
	/// </summary>
	internal abstract class BaseTransformer
	{
		#region Fields

		private readonly string _xsltResourceName;

		#endregion

		#region Constructors

		protected BaseTransformer(string xsltName)
		{
			this._xsltResourceName = string.Format(CultureInfo.InvariantCulture, "FinlogiK.FxCop.Statistics.XsltFiles.{0}.xslt", xsltName);
		}

		#endregion

		#region Methods

		internal XmlDocument TransformFxCopOutput(string inputPath)
		{
			if (inputPath == null) throw new ArgumentNullException("inputPath");

			using (Stream outputStream = new MemoryStream())
			{
				this.TransformFxCopOutput(inputPath, outputStream);
				outputStream.Position = 0;

				XmlDocument document = new XmlDocument();
				document.Load(outputStream);

				return document;
			}
		}

		private void TransformFxCopOutput(string inputPath, Stream outputStream)
		{
			using (Stream stylesheetStream = this.GetType().Assembly.GetManifestResourceStream(this._xsltResourceName))
			{
				XmlReader stylesheetReader = new XmlTextReader(stylesheetStream);

				XslCompiledTransform transform = new XslCompiledTransform(false);
				transform.Load(stylesheetReader);

				transform.Transform(inputPath, null, outputStream);
			}
		}

		#endregion
	}
}